﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Baosight.Platform.Core.UI.Controls;
using System.Windows.Browser;
using Baosight.Platform.Core.ServiceModel;
using Baosight.Platform.Core;
using Telerik.Windows.Controls;
using Baosight.ZNH.ZMCommon;
using Baosight.ZNH.ZMCommon.ChildWindows;

namespace Baosight.ZNH.ZMCD.UI
{
    public partial class ZMCD01 : EFViewCmes
    {
        private EFTreeItem item;    //记录选中的树节点
        private bool RefreshParentNode = true;   //判断是否刷新父节点
        public ZMCD01()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(ZMCD01_Loaded);

        }

        private void ZMCD01_Loaded(object sender, RoutedEventArgs e)
        {
            this.tree.Refresh();
        }

        /// <summary>
        /// 点击树节点，右侧页面刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tree_Selected(object sender, Telerik.Windows.RadRoutedEventArgs e)
        {
            Dictionary<string, string> args = new Dictionary<string, string>();
            string _value = "";
            if (this.tree.SelectedItems.Count > 0)
            {
                item = this.tree.SelectedItems[0] as EFTreeItem;
                _value = item.ItemObject.GetType().GetProperty("label").GetValue(item.ItemObject, null) as string;
                args.Add("fdDirId", _value);
                _value = item.ItemObject.GetType().GetProperty("limit").GetValue(item.ItemObject, null) as string;
                args.Add("Limit", _value);
            }
            if (args == null)
            {
                BaseTools.OpenEFWindowAlert("请选择目录！", AlertWin_Closed);
                return;
            }

            if ("-1".Equals(args["Limit"]))
            {
                this.container.Content = null;
                return;
            }

            this.container.LoadView<EFCustomViewContainerPanel>("ZMCD02", args);
        }

        /// <summary>
        /// 页面初始化的时候，选中树的根节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tree_ItemPrepared(object sender, RadTreeViewItemPreparedEventArgs e)
        {
            if (e.PreparedItem == null)
            {
                return;
            }
            EFTreeItem treeItem = e.PreparedItem as EFTreeItem;
            if (treeItem.Level == 0 && treeItem.Index == 0)
            {
                this.tree.SelectedItem = treeItem;//选中
                treeItem.ExpandItem();//展开
            }
        }


        #region  新增修改按钮
        /// <summary>
        /// 点击新增按钮，弹出新增页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OnInsertButtonClick(object sender, RoutedEventArgs e)
        {
            RefreshParentNode = false;
            TempButton = sender as Button;
            TempButton.IsEnabled = false;
            if (this.tree.SelectedItems.Count <= 0)
            {
                BaseTools.OpenEFWindowAlert("请选择目录！", Window_Closed);
                return;
            }

            EFTreeItem _item = this.tree.SelectedItems[0] as EFTreeItem;
            if ("公用目录".Equals(_item.ItemObject.GetType().GetProperty("type").GetValue(_item.ItemObject, null)) ||
                "指定目录".Equals(_item.ItemObject.GetType().GetProperty("type").GetValue(_item.ItemObject, null)))
            {
                BaseTools.OpenEFWindowAlert("只能添加个人目录或者部门目录！", AlertWin_Closed);
                return;
            }

            EIInfo eiInfo = new EIInfo();
            base.OnInsertButtonClickPopup(eiInfo, "文档目录-新增", "insert", null, sender, e);
        }

        /// <summary>
        /// 点击修改按钮，弹出新增页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OnUpdateButtonClick(object sender, RoutedEventArgs e)
        {
            RefreshParentNode = true;
            TempButton = sender as Button;
            TempButton.IsEnabled = false;
            if (this.tree.SelectedItems.Count <= 0)
            {
                BaseTools.OpenEFWindowAlert("请选择目录！", AlertWin_Closed);
                return;
            }

            EFTreeItem _item = this.tree.SelectedItems[0] as EFTreeItem;
            if (_item.IsRootItem)
            {
                BaseTools.OpenEFWindowAlert("根目录不能修改！", AlertWin_Closed);
                return;
            }

            if ("公用目录".Equals(_item.ItemObject.GetType().GetProperty("type").GetValue(_item.ItemObject, null)) ||
                "指定目录".Equals(_item.ItemObject.GetType().GetProperty("type").GetValue(_item.ItemObject, null)))
            {
                BaseTools.OpenEFWindowAlert("只能修改个人目录或者部门目录！", AlertWin_Closed);
                return;
            }

            if (!this.EIDataContext.GetAttribute("userId").Equals(_item.ItemObject.GetType().GetProperty("creator").GetValue(_item.ItemObject, null)))
            {
                BaseTools.OpenEFWindowAlert("不能修改，只有该目录的创建人可以修改此目录！", AlertWin_Closed);
                return;
            }

            EIRow eirow = (_item.ItemObject as UIBaseEntity).GetEIRow();
            var _value = eirow["label"];

            HttpServiceAgent agent = new HttpServiceAgent();
            EIInfo eiInfo = new EIInfo();
            eiInfo.Attributes.Add("fdDirId", _value);
            eiInfo.Attributes.Add(EIConstants.ServiceNameKey, "ZMCD01");
            eiInfo.Attributes.Add(EIConstants.MethodNameKey, "queryDirInfo");

            agent.CallService(eiInfo, OnDoQueryWorkCompleted); 
        }

        /// <summary>
        /// 查询要修改的目录的回调函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnDoQueryWorkCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status != -1)
            {
                OpenPopup(e.EIInfo, "文档目录-修改", "update", null);             
            }
            else
            {
                BaseTools.OpenEFWindowAlert("未查询到该目录的信息，不能修改！", AlertWin_Closed);
            }
        }


        /// <summary>
        /// 弹出窗口关闭时执行的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Closed(object sender, WindowClosedEventArgs e)
        {
            if (e.DialogResult == true)
            {
                //刷新目录树
                RefreshTree();
            }

            //按钮生效
            base.TempButtonOpen(true);
        }


        /// <summary>
        /// 新增或修改之前的数据传输
        /// 构造新增页面内容、弹出页面
        /// </summary>
        /// <param name="eIInfo"></param>
        /// <param name="title"></param>
        public override void OpenPopup(EIInfo _eIInfo, string _title, string _dialogType, string _args)
        {
            ZMCD12 view = new ZMCD12(_dialogType);//构造一个新的修改页面
            view.EIDataContext = new Platform.Core.UI.EIDataContext();
            view.EIDataContext.Update(_eIInfo);

            if (_dialogType.Equals("insert"))
            {
                EFTreeItem _item = this.tree.SelectedItems[0] as EFTreeItem;
                var _value = _item.ItemObject.GetType().GetProperty("label").GetValue(_item.ItemObject, null);
                view.fdSuperDirId.Value = _value;
                _value = _item.ItemObject.GetType().GetProperty("type").GetValue(_item.ItemObject, null);
                view.fdDirType.Value = _value;
            }

            CmesWindows _popup = new CmesWindows();//构造一个弹出页面
            _popup.ResizeMode = ResizeMode.NoResize;//设置不能修改窗口大小
            _popup.Header = _title == null ? "" : _title;//设置Title
            _popup.Content = view;//让新增页面在弹出窗口显示
            _popup.Closed += new EventHandler<WindowClosedEventArgs>(Window_Closed);
            _popup.ShowDialog();//模态显示弹出窗口
        }
        #endregion

        #region 删除按钮
        /// <summary>
        /// 删除按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OnDeleteButtonClick(object sender, RoutedEventArgs e)
        {
            RefreshParentNode = true;
            TempButton = sender as Button;
            TempButton.IsEnabled = false;

            if (this.tree.SelectedItems.Count <= 0)
            {
                BaseTools.OpenEFWindowAlert("请选择目录！", AlertWin_Closed);
                return;
            }

            EFTreeItem _item = this.tree.SelectedItems[0] as EFTreeItem;
            if (_item.IsRootItem)
            {
                BaseTools.OpenEFWindowAlert("根目录不能删除！", AlertWin_Closed);
                return;
            }

            if ("公用目录".Equals(_item.ItemObject.GetType().GetProperty("type").GetValue(_item.ItemObject, null)) ||
                "指定目录".Equals(_item.ItemObject.GetType().GetProperty("type").GetValue(_item.ItemObject, null)))
            {
                BaseTools.OpenEFWindowAlert("只能删除个人目录或者部门目录！", AlertWin_Closed);
                return;
            }

            if (!this.EIDataContext.GetAttribute("userId").Equals(_item.ItemObject.GetType().GetProperty("creator").GetValue(_item.ItemObject, null)))
            {
                BaseTools.OpenEFWindowAlert("不能删除，只有该目录的创建人可以删除此目录！", AlertWin_Closed);
                return;
            }

            EIRow eirow = (_item.ItemObject as UIBaseEntity).GetEIRow();
            var _value = eirow["label"];
            HttpServiceAgent agent = new HttpServiceAgent();
            EIInfo eiInfo = new EIInfo();
            eiInfo.Attributes.Add("fdDirId", _value);
            eiInfo.Attributes.Add(EIConstants.ServiceNameKey, "ZMCD01");
            eiInfo.Attributes.Add(EIConstants.MethodNameKey, "canDelete");

            agent.CallService(eiInfo, CanDeleteQueryCompleted);             
        }

        /// <summary>
        /// 判断是否能删除的回调函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CanDeleteQueryCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status != -1)
            {
                BaseTools.OpenEFWindowConfirm("确定删除所选择目录", DeleteConfirmClosed);
                return;
            }
            BaseTools.OpenEFWindowAlert(e.EIInfo.Msg, WindowAlertClosed);
        }

        /// <summary>
        /// 删除确认框的回调
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeleteConfirmClosed(object sender, WindowClosedEventArgs e)
        {
            if (e.DialogResult == null)
            {
                this.TempButtonOpen(true);
                return;
            }
            if (e.DialogResult.Value)
            {
                EIInfo subInfo = new EIInfo();
                subInfo.Attributes.Add(EIConstants.ServiceNameKey, "ZMCD01");
                subInfo.Attributes.Add(EIConstants.MethodNameKey, "delete");

                subInfo.AddBlock(EIConstants.ResultBlock);
                EIColumn col = new EIColumn();
                col.Name = "fdKeyId";
                subInfo.GetBlock(EIConstants.ResultBlock).AddColumn(col);

                EFTreeItem _item = this.tree.SelectedItems[0] as EFTreeItem;
                var _value = _item.ItemObject.GetType().GetProperty("label").GetValue(_item.ItemObject, null);
                EIRow row = new EIRow();
                row.Add("fdKeyId", _value);
                subInfo.GetBlock(EIConstants.ResultBlock).AddRow(row);

                this.Submit(subInfo, DeleteCompleted);  //回调函数DeleteCompleted
            }
            else
            {
                this.TempButtonOpen(true);
            }
        }

        /// <summary>
        /// 删除后的回调函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void DeleteCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status != -1)
            {
                RefreshTree();
            }
            else
            {
                BaseTools.OpenEFWindowAlert(e.EIInfo.Msg, null);
            }

            this.TempButtonOpen(true);
        }

        #endregion

        /// <summary>
        /// 提示框关闭时的回调函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AlertWin_Closed(object sender, WindowClosedEventArgs e)
        {
            //按钮生效
            base.TempButtonOpen(true);
        }

        /// <summary>
        /// 新增修改删除目录时，刷新树节点
        /// </summary>
        private void RefreshTree()
        {
            Dictionary<string, string> args = new Dictionary<string, string>();
            string _value = "";
            if (item != null)
            {
                if (RefreshParentNode == true)
                {
                    _value = (item.Parent as EFTreeItem).ItemObject.GetType().GetProperty("label").GetValue((item.Parent as EFTreeItem).ItemObject, null) as string;
                    args.Add("node", _value);
                    _value = (item.Parent as EFTreeItem).ItemObject.GetType().GetProperty("type").GetValue((item.Parent as EFTreeItem).ItemObject, null) as string;
                    args.Add("type", _value);
                }
                else
                {
                    _value = item.ItemObject.GetType().GetProperty("label").GetValue(item.ItemObject, null) as string;
                    args.Add("node", _value);
                    _value = item.ItemObject.GetType().GetProperty("type").GetValue(item.ItemObject, null) as string;
                    args.Add("type", _value);
                }
            }
            BaseTools.RefreshTree("ZMCD01", "query", args, OnDoWorkCompleted);
        }

        /// <summary>
        /// 刷新树的回调方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnDoWorkCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            this.tree.EIDataContext = new Platform.Core.UI.EIDataContext();
            this.tree.EIDataContext.Update(e.EIInfo);
            item.IsLoadOnDemandEnabled = true;
            if (RefreshParentNode == true)
            {
                EFTreeItem parent = item.Parent as EFTreeItem;
                string node = item.ItemObject.GetType().GetProperty("label").GetValue(item.ItemObject, null) as string;
                parent.Items.Clear();
                parent.CollapseItem();
                parent.ExpandItem();
                item = BaseTools.FindTreeItem(parent.Items, node, "label") as EFTreeItem;
                if (item != null)
                {
                    this.tree.SelectedItem = item;
                }
                else
                {
                    this.tree.SelectedItem = parent;
                }
                return;
            }
            item.Items.Clear();
            item.CollapseItem();
            item.ExpandItem();
        }
    }
}
